<template>
  <div class="payment-page">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="back-button" @click="goBack">
        <van-icon name="arrow-left" size="24" color="#333" />
      </div>
      <div class="title">确认订单</div>
      <div class="right-space"></div>
    </div>

    <!-- 配送地址 -->
    <div class="delivery-address">
      <div class="address-info">
        <van-icon name="location-o" size="22" color="#666" />
        <div class="address-content">
          <div class="location-name">{{ selectedAddress.location || '泸州职业技术学院-东门' }}</div>
          <div class="contact-info">{{ selectedAddress.name || '蒋先生' }} {{ selectedAddress.phone || '19915811026' }}</div>
        </div>
        <van-icon name="arrow" size="16" color="#999" />
      </div>
      
      <!-- 配送时间 -->
      <div class="delivery-time">
        <div class="time-label">预计时间</div>
        <div class="time-value">{{ deliveryTimeRange }}</div>
        <van-icon name="arrow" size="16" color="#999" />
      </div>
      
      <!-- 点餐提示 -->
      <div class="delivery-note">
        <van-icon name="volume-o" size="16" color="#ff5339" />
        <span>点餐请适量，环保又健康</span>
      </div>
    </div>

    <!-- 商家信息 -->
    <div class="merchant-info">
      <div class="merchant-name">窝鸡王（泸州万象汇店）</div>
      <div class="merchant-tag">商家自配</div>
    </div>

    <!-- 商品列表 -->
    <div class="order-items">
      <div class="order-item" v-for="(item, index) in cartItems" :key="index">
        <div class="item-image">
          <img :src="item.img || require('@/assets/images/product/food.png')" alt="商品图片" />
        </div>
        <div class="item-info">
          <div class="item-name">{{ item.name }}</div>
          <div class="item-quantity">x{{ item.quantity }}</div>
          <div class="item-price">¥{{ Math.max(0, (item.price - (item.discount || 0)) * item.quantity).toFixed(2) }}</div>
        </div>
      </div>
      
      <!-- 打包费 -->
      <div class="fee-item">
        <div class="fee-label">打包费</div>
        <div class="fee-value">¥{{ packagingFee.toFixed(2) }}</div>
      </div>
      
      <!-- 配送费 -->
      <div class="fee-item">
        <div class="fee-label">配送费</div>
        <div class="fee-value">¥{{ deliveryFee.toFixed(2) }}</div>
        <div class="fee-tag">活动减7.2元配送费</div>
      </div>
      
      <!-- 优惠信息 -->
      <div class="discount-item">
        <div class="discount-label">已享优惠</div>
        <div class="discount-value">红包优惠</div>
        <div class="discount-amount">-¥{{ redPacketDiscount.toFixed(2) }}</div>
      </div>
    </div>

    <!-- 优惠券区域 -->
    <div class="coupon-area">
      <div class="coupon-item">
        <div class="coupon-label">美团红包</div>
        <div class="coupon-value">已使用</div>
        <div class="coupon-amount">{{ redPacketDiscount }}元红包</div>
        <van-icon name="arrow" size="16" color="#999" />
      </div>
      
      <div class="coupon-item">
        <div class="coupon-label">商家代金券</div>
        <div class="coupon-value">暂无可用</div>
        <van-icon name="arrow" size="16" color="#999" />
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div class="checkout-bar">
      <div class="checkout-info">
        <div class="total-price">合计 <span>¥{{ finalTotal.toFixed(2) }}</span></div>
        <div class="discount-info">已优惠¥{{ totalDiscount.toFixed(2) }}</div>
      </div>
      
      <div class="submit-button" @click="submitOrder">
        提交订单
      </div>
    </div>

    <!-- 支付大气提示弹层 -->
    <transition name="fade">
      <div v-if="showPayStatus" class="meituan-toast-overlay">
        <div class="meituan-toast-content" :class="payStatusType">
          <img v-if="payStatusType==='loading'" src="@/assets/images/meituan.png" class="meituan-toast-logo" />
          <i v-if="payStatusType==='success'" class="meituan-toast-icon success"></i>
          <i v-if="payStatusType==='fail'" class="meituan-toast-icon fail"></i>
          <div class="meituan-toast-message">
            {{ payStatusMessage }}
          </div>
          <div v-if="payStatusType==='loading'" class="meituan-toast-spinner"></div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import { Toast } from 'vant'

export default {
  name: 'Payment',
  data() {
    return {
      useMeituanPay: true,
      deliveryTimeRange: '',
      timer: null,
      isSubmitting: false, // 防止重复提交
      showPayStatus: false,
      payStatusType: '', // loading/success/fail
      payStatusMessage: '',
      payStatusTimer: null
    }
  },
  computed: {
    ...mapState('cart', ['items', 'selectedAddress']),
    ...mapGetters('cart', [
      'totalPrice',
      'deliveryFee',
      'packagingFee',
      'redPacketDiscount',
      'originalTotal',
      'itemsDiscountedTotal',
      'totalDiscount'
    ]),
    cartItems() {
      return this.items;
    },
    finalTotal() {
      return this.totalPrice;
    }
  },
  created() {
    console.log('Payment component created');
    this.updateDeliveryTime();
    this.timer = setInterval(this.updateDeliveryTime, 60000);
  },
  mounted() {
    console.log('Payment component mounted');
    console.log('Cart items in payment:', this.items);
  },
  beforeUnmount() {
    console.log('Payment component unmounting');
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    ...mapActions('cart', ['clearCart']),
    goBack() {
      this.$router.go(-1)
    },
    async submitOrder() {
      if (this.isSubmitting) return;
      this.isSubmitting = true;

      // 使用自定义大气支付loading
      this.showPayStatus = true;
      this.payStatusType = 'loading';
      this.payStatusMessage = '正在为您支付，请稍候...';
      if (this.payStatusTimer) clearTimeout(this.payStatusTimer);

      try {
        await new Promise(resolve => setTimeout(resolve, 1500));
        // 先保存订单到localStorage
        const order = {
          id: Date.now(),
          shopName: '窝鸡王（泸州万象汇店）',
          shopTag: '商家自配',
          shopImg: require('@/assets/images/product/product1title.png'),
          items: this.cartItems,
          total: Number(this.finalTotal),
          status: '进行中',
          time: new Date().toLocaleString(),
        };
        let orders = JSON.parse(localStorage.getItem('orders') || '[]');
        orders.unshift(order);
        localStorage.setItem('orders', JSON.stringify(orders));
        // 再清空购物车
        await this.clearCart();
        this.payStatusType = 'success';
        this.payStatusMessage = '支付成功，正在跳转订单页';
        this.payStatusTimer = setTimeout(() => {
          this.showPayStatus = false;
          this.$router.replace('/order');
        }, 2000);
      } catch (error) {
        this.payStatusType = 'fail';
        this.payStatusMessage = '支付失败，请重试';
        this.payStatusTimer = setTimeout(() => {
          this.showPayStatus = false;
        }, 2000);
      } finally {
        this.isSubmitting = false;
      }
    },
    // 更新配送时间范围
    updateDeliveryTime() {
      const now = new Date();
      const start = new Date(now);
      const end = new Date(now.getTime() + 30 * 60000); // 30分钟后

      const startHour = start.getHours().toString().padStart(2, '0');
      const startMinute = start.getMinutes().toString().padStart(2, '0');
      const endHour = end.getHours().toString().padStart(2, '0');
      const endMinute = end.getMinutes().toString().padStart(2, '0');

      this.deliveryTimeRange = `${startHour}:${startMinute}-${endHour}:${endMinute}送达`;
    }
  }
}
</script>

<style lang="less" scoped>
.payment-page {
  width: 750px;
  margin: 0 auto;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 140px;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  height: 88px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  
  .back-button {
    width: 44px;
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .title {
    font-size: 36px;
    font-weight: bold;
    color: #333;
  }
  
  .right-space {
    width: 44px;
  }
}

.delivery-address {
  margin-top: 98px;
  background-color: #fff;
  padding: 30px;
  
  .address-info {
    display: flex;
    align-items: flex-start;
    margin-bottom: 20px;
    
    .van-icon {
      margin-top: 6px;
      flex-shrink: 0;
    }
    
    .address-content {
      flex: 1;
      margin-left: 20px;
      
      .location-name {
        font-size: 32px;
        font-weight: bold;
        color: #333;
        margin-bottom: 10px;
      }
      
      .contact-info {
        font-size: 28px;
        color: #666;
      }
    }
  }
  
  .delivery-time {
    display: flex;
    align-items: center;
    padding: 20px 0;
    border-top: 1px solid #f6f6f6;
    border-bottom: 1px solid #f6f6f6;
    
    .time-label {
      font-size: 28px;
      color: #666;
      margin-right: 20px;
    }
    
    .time-value {
      flex: 1;
      font-size: 28px;
      color: #ff8000;
      font-weight: bold;
    }
  }
  
  .delivery-note {
    display: flex;
    align-items: center;
    padding-top: 20px;
    
    span {
      margin-left: 10px;
      font-size: 26px;
      color: #666;
    }
  }
}

.merchant-info {
  margin-top: 20px;
  background-color: #fff;
  padding: 30px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .merchant-name {
    font-size: 32px;
    font-weight: bold;
    color: #333;
  }
  
  .merchant-tag {
    font-size: 24px;
    color: #999;
    background-color: #f8f8f8;
    padding: 5px 10px;
    border-radius: 4px;
  }
}

.order-items {
  background-color: #fff;
  margin-top: 2px;
  padding: 0 30px;
  
  .order-item {
    display: flex;
    padding: 30px 0;
    border-bottom: 1px solid #f6f6f6;
    
    .item-image {
      width: 120px;
      height: 120px;
      margin-right: 20px;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 8px;
      }
    }
    
    .item-info {
      flex: 1;
      position: relative;
      
      .item-name {
        font-size: 30px;
        font-weight: bold;
        color: #333;
        margin-bottom: 10px;
      }
      
      .item-quantity {
        font-size: 28px;
        color: #999;
      }
      
      .item-price {
        position: absolute;
        right: 0;
        top: 50%;
        transform: translateY(-50%);
        font-size: 30px;
        font-weight: bold;
        color: #333;
      }
    }
  }
  
  .fee-item {
    display: flex;
    align-items: center;
    padding: 25px 0;
    border-bottom: 1px solid #f6f6f6;
    
    .fee-label {
      flex: 1;
      font-size: 28px;
      color: #333;
    }
    
    .fee-value {
      font-size: 28px;
      color: #333;
      margin-right: 10px;
    }
    
    .fee-tag {
      font-size: 24px;
      color: #999;
    }
  }
  
  .discount-item {
    display: flex;
    align-items: center;
    padding: 25px 0;
    
    .discount-label {
      flex: 1;
      font-size: 28px;
      color: #333;
    }
    
    .discount-value {
      font-size: 28px;
      color: #999;
      margin-right: 10px;
    }
    
    .discount-amount {
      font-size: 28px;
      color: #ff5339;
    }
  }
}

.coupon-area {
  margin-top: 20px;
  background-color: #fff;
  
  .coupon-item {
    display: flex;
    align-items: center;
    padding: 30px;
    border-bottom: 1px solid #f6f6f6;
    
    .coupon-label {
      flex: 1;
      font-size: 28px;
      color: #333;
    }
    
    .coupon-value {
      font-size: 28px;
      color: #999;
      margin-right: 10px;
    }
    
    .coupon-amount {
      font-size: 28px;
      color: #ff5339;
      margin-right: 10px;
    }
  }
}

.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 99;
  
  .payment-options {
    padding: 20px 30px;
    border-bottom: 1px solid #f6f6f6;
    
    .payment-method {
      display: flex;
      align-items: center;
      
      .payment-icon {
        width: 36px;
        height: 36px;
        margin-right: 10px;
      }
      
      span {
        font-size: 26px;
        color: #333;
      }
      
      .discount-highlight {
        color: #ff5339;
        margin-left: 5px;
      }
    }
  }
  
  .checkout-info {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    padding: 20px 30px;
    
    .total-price {
      font-size: 26px;
      color: #333;
      
      span {
        font-size: 32px;
        font-weight: bold;
        color: #ff5339;
      }
    }
    
    .discount-info {
      font-size: 22px;
      color: #999;
    }
  }
  
  .submit-button {
    background-color: #ffd161;
    color: #333;
    font-size: 32px;
    font-weight: bold;
    height: 98px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:active {
      opacity: 0.9;
    }
    
    &.submitting {
      opacity: 0.7;
      pointer-events: none;
    }
  }
}

.meituan-toast-overlay {
  position: fixed;
  left: 0; right: 0; top: 0; bottom: 0;
  z-index: 9999;
  background: rgba(0,0,0,0.18);
  display: flex;
  align-items: center;
  justify-content: center;
}
.meituan-toast-content {
  min-width: 320px;
  min-height: 180px;
  background: #ffd161;
  border-radius: 18px;
  box-shadow: 0 8px 32px rgba(0,0,0,0.18);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 36px 48px 32px 48px;
  position: relative;
  animation: popIn 0.25s;
}
.meituan-toast-logo {
  width: 64px;
  height: 64px;
  margin-bottom: 18px;
}
.meituan-toast-message {
  font-size: 32px;
  color: #333;
  font-weight: bold;
  margin: 18px 0 0 0;
  text-align: center;
}
.meituan-toast-spinner {
  margin-top: 18px;
  width: 40px;
  height: 40px;
  border: 5px solid #fff2b2;
  border-top: 5px solid #ffb800;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
.meituan-toast-icon {
  font-size: 64px;
  margin-bottom: 18px;
  display: inline-block;
}
.meituan-toast-icon.success::before {
  content: '\2714'; /* 大勾 */
  color: #00c800;
}
.meituan-toast-icon.fail::before {
  content: '\2716'; /* 大叉 */
  color: #ff5339;
}
.meituan-toast-content.success {
  background: #fff;
}
.meituan-toast-content.fail {
  background: #fff;
}
@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
@keyframes popIn {
  0% { transform: scale(0.7); opacity: 0; }
  100% { transform: scale(1); opacity: 1; }
}
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style> 